<template>
	<view class="container">
		<view class="nav">
			<text :class="{ active: navActiveIndex==0 }" @click="pageScrollTo(0,'banner')">商品</text>
			<text :class="{ active: navActiveIndex==1 }" @click="pageScrollTo(1,'param')">参数</text>
			<text :class="{ active: navActiveIndex==2 }" @click="pageScrollTo(2,'detail')">详情</text>
		</view>
		<uni-swiper-dot :info="goodsInfo.banner" mode="round" :dots-styles="dotStyle" :current="currentBannerIndex">
			<swiper class="banner" circular id="banner" @change="bannerChange">
				<swiper-item v-for="(item, index) in goodsInfo.banner" :index="index" :key="index">
					<image mode="scaleToFill" :src="item.url" @click="previewBannerImage(index)"></image>
				</swiper-item>
			</swiper>
		</uni-swiper-dot>
<!--		<view class="ad">-->
<!--			<image mode="scaleToFill" :src="ossHost+'/yi_heng/goods_detail_ad.png'"></image>-->
<!--		</view>-->
		<view class="goods-info">
			<view class="price"><text>￥</text>{{ goodsShowInfo.goodsPrice / 100 }}</view>
			<view class="title"><text :selectable="true" :user-select="true">{{ goodsShowInfo.goodsName }}</text></view>
			<view class="summary"><text :selectable="true" :user-select="true">{{ goodsShowInfo.goodsDescription }}</text></view>
		</view>
		<view class="goods-param" id="param">
			<view class="title">基本参数</view>
			<view class="key-val" v-for="(item,index) in goodsShowInfo.goodsParam" :index="index" :key="index">
				<view class="key">{{ item.specName }}</view>
				<view class="val">{{ item.specValue }}</view>
			</view>
		</view>
		<view class="goods-detail" style="padding-bottom: 160rpx;" id="detail">
			<rich-text :nodes="goodsShowInfo.goodsDetail" @click="previewDetailImage"></rich-text>
		</view>

		<view class="goods-carts">
			<uni-goods-nav :options="options" :fill="true" :button-group="buttonGroup" @click="onClick"
				@buttonClick="openPopup" />
		</view>

		<uni-popup ref="popup" type="bottom">
			<view class="spec">
				<view class="close">
					<uni-icons type="closeempty" size="24" color="#8F8F8F" @click="closePopup()"></uni-icons>
				</view>
				<view class="info">
					<view class="left">
						<image mode="scaleToFill" :src="goodsShowInfo.thumbnail"
							@click="previewThumbnailImage()"></image>
					</view>
					<view class="right">
						<view class="title"><text :selectable="true">{{ goodsShowInfo.goodsName }}</text></view>
						<view class="price"><text>￥</text>{{ goodsShowInfo.goodsPrice/100 }}</view>
					</view>
				</view>
				<view class="spec-list">
					<view v-for="(item,index) in allSpecList" :key="index" class="item">
						<view class="spec-name">
							{{ item.specName }}
						</view>
						<view class="spec-value">
							<text v-for="(item2,index2) in item.specValueList" :key="index2"
								:class="{ active: selected.indexOf(item2.specValue) > -1, disable: !isCanSelect(item2.specValue,index) && selected.indexOf(item2.specValue) === -1 }"
								@click=" isCanSelect(item2.specValue,index)  && specSelect(item2.specValue,index)">
								{{ item2.specValue }}
							</text>
						</view>
					</view>
				</view>
				<view class="spec-num">
					<view class="left">购买数量</view>
					<view class="right">
						<uni-number-box v-model="goodsNum" :min="1" :max="goodsShowInfo.goodsStorage" />
					</view>
				</view>
				<button v-if="popupType == 1" type="warn" class="spec-btn" @click="addCart()">加入购物车</button>
				<button v-else-if="popupType == 2" type="warn" class="spec-btn" @click="toOrder()">立即购买</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import { GoodsApi } from '@/api/food/GoodsApi'
	import { DictApi } from '@/api/DictApi'

	export default {
		data() {
			return {
                Config:this.$Config,
                Common:this.$Common,
                Auth:this.$Auth,
                ShareUtil:this.$ShareUtil,
                State:this.$store.state,

				goodsShowInfo: {},
				goodsInfo: {},
				navActiveIndex: 0,

				bannerImageArr: [],
				detailImageArr: [],
				options: [{
					icon: 'home',
					text: '主页',
				}, {
					icon: 'chat',
					text: '客服'
				}, {
					icon: 'cart',
					text: '购物车',
					info: 0
				}],
				buttonGroup: [{
						text: '加入购物车',
						backgroundColor: 'linear-gradient(90deg, #FFCD1E, #FF8A18)',
						color: '#fff'
					},
					{
						text: '立即购买',
						backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
						color: '#fff'
					}
				],

				//处理规格数据start
				allSpecList: [], //规格完整数据
				items: [], //简化后的规格数据
				result: [], //商品的规格值
				selected: [], //已选择的规格项
				data: {}, //关键字规格集合
				//处理规格数据end

				popupType: 1,
				goodsNum: 1,
				dict: {},

				dotStyle: {
					backgroundColor: 'rgba(255, 255, 255, .5)',
					border: 'none',
					color: '#fff',
					selectedBackgroundColor: 'rgba(255, 255, 255, .9)',
					selectedBorder: 'none'
				},
				currentBannerIndex: 0
			}
		},
		onLoad(e) {
			let that = this

			that.getGoodsMainDetail(e.mainGoodsId, function() {
				that.showGoodsInfo(that.goodsInfo)
				that.initSpec()

				if (e.goodsId) that.setChildGoodsInfo(e.goodsId)
			})

            DictApi.getDict().then((response) => {
                this.dict = response
            })

			// 分享
			// #ifdef MP-WEIXIN
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			})
			// #endif
		},

		methods: {
			initPage: function() {
				if (this.Auth.isLogin()) {
					this.countShoppingCart()
				}
			},
			getGoodsMainDetail(mainGoodsId, callback) {
                GoodsApi.getGoodsMainDetail(mainGoodsId).then((response) => {
					this.goodsInfo = response
					callback()
				})
			},
            convertSpec(dataList){
                let result = []
                dataList.forEach(function (item, index, arr) {
                    let i = -1
                    result.forEach(function (cItem, cIndex, cArr) {
                        if (item.specId === cItem.specId) i = cIndex
                    })

                    if (i > -1) {
                        result[i].specValueList.push({
                            specValue: item.specValue,
                            specValueId: item.specValueId
                        })
                    } else {
                        let specObj = {
                            specId: item.specId,
                            specName: item.specName,
                            specType: item.specType,
                            specValueList: [{
                                specValue: item.specValue,
                                specValueId: item.specValueId
                            }]
                        }

                        result.push(specObj)
                    }
                })

                return result
            },
			showGoodsInfo(goodsData) {
				this.goodsShowInfo = goodsData
				this.goodsShowInfo.goodsStorage = parseInt(goodsData.goodsStorage)

				let goodsDetail = this.goodsShowInfo.goodsDetail
				goodsDetail = goodsDetail ? goodsDetail.replace(RegExp("<img", "g"), '<img style="width:100%;height:auto;display:block;"') : ''

				this.goodsShowInfo.goodsDetail = goodsDetail
                this.detailImageArr = this.Common.regexHtmlImg(goodsDetail)

				this.bannerImageArr = []
				this.goodsInfo.banner.forEach(item => {
					this.bannerImageArr.push(item.url)
				})

				this.allSpecList = this.convertSpec(goodsData.goodsSpecValueList.filter((item) => item.specType === 1))
				this.goodsShowInfo['goodsParam'] = goodsData.goodsSpecValueList.filter((item) => item.specType === 2)
			},
			previewBannerImage(index) {
                uni.previewImage({
                    current: index,
                    urls: this.bannerImageArr
                })
			},
			previewDetailImage() {
                uni.previewImage({
                    current: 0,
                    urls: this.detailImageArr
                })
			},
			previewThumbnailImage() {
                uni.previewImage({
                    current: 0,
                    urls: [this.goodsShowInfo.thumbnail]
                })
			},
			countShoppingCart() {
				ShoppingCartApi.countShoppingCart({}).then((response) => {
					this.options[2].info = response
				})
			},
			//初始化设置默认子商品
			setChildGoodsInfo(goodsId) {
				if (!goodsId) return

				let childList = this.goodsInfo.goodsSpecList.filter(v => v.id == goodsId)
				if (childList.length === 0) return

				let childInfo = childList[0]
				this.selected = childInfo.specKey.split('-')
				this.getChildGoodsByKey()
			},

			getChildGoodsByKey() {
				let selected = Object.assign([], this.selected)
				selected = selected.filter(v => v != null)
				if (selected.length !== this.allSpecList.length) {
					this.showGoodsInfo(this.goodsInfo)
				} else {
					let key = selected.join('-')
					let childGoodsList = this.goodsInfo.goodsSpecList.filter(v => v.specKey == key)
					if (childGoodsList.length == 1) {
						let childGoodsInfo = childGoodsList[0]

						let newGoods = Object.assign({}, this.goodsInfo)
						newGoods.id = childGoodsInfo.id
						newGoods.goodsName = childGoodsInfo.goodsName
						newGoods.goodsPrice = childGoodsInfo.goodsPrice
						newGoods.goodsStorage = childGoodsInfo.goodsStorage
						if (childGoodsInfo.goodsDetail) {
							newGoods.goodsDetail = childGoodsInfo.goodsDetail
						}
						if (childGoodsInfo.thumbnail) {
							newGoods.thumbnail = childGoodsInfo.thumbnail
						}
						if (childGoodsInfo.banner && childGoodsInfo.banner.length > 0) {
							newGoods.banner = childGoodsInfo.banner
						}

						this.showGoodsInfo(newGoods)
					}
				}
			},

			//初始化规格
			initSpec() {
				let that = this
				that.allSpecList.forEach(item => {
					let spec = []
					item.specValueList.forEach(value => {
						spec.push(value.specValue)
					})

					that.items.push(spec)
				})

				that.goodsInfo.goodsSpecList.forEach(item => {
					that.result[item.specKey] = {
						remain: item.goodsStorage,
						price: item.goodsPrice
					}
				})
			},
			//判断是否可选
			isCanSelect(value, index) {
				let newSelect = Object.assign([], this.selected)
				newSelect[index] = value

				let remain = this.getRemainByKey(newSelect)

				return remain > 0
			},
			//点击规格值
			specSelect(value, index) {
				if (this.selected[index] === value) {
					this.selected[index] = null
				} else {
					this.selected[index] = value
				}

				this.getChildGoodsByKey()
				this.goodsNum = 1
			},
			//取出关键字下的库存
			getRemainByKey(selected) {
				let that = this

				selected = selected.filter(v => v != null)
				const key = selected.join('-')

				if (typeof that.data[key] !== 'undefined') {
					return that.data[key]
				}

				if (selected.length === that.items.length) {
					return that.result[key] ? that.data[key] = that.result[key].remain : that.data[key] = 0
				}

				let remain = 0
				let tempSelected = []

				for (let i = 0; i < that.items.length; i++) {
					const exist = that.items[i].find(_item => _item === selected[0])
					if (exist && selected.length > 0) {
						tempSelected.push(selected.shift())
					} else {
						that.items[i].forEach(_item => {
							remain += that.getRemainByKey(tempSelected.concat(_item, selected))
						})
						break
					}
				}
				return that.data[key] = remain
			},
			onClick(e) {
				let that = this
				if (e.index === 0) {
					uni.switchTab({
						url: '/pages/index'
					});
				} else if (e.index === 1) {
					uni.makePhoneCall({
						phoneNumber: that.dict.config.serviceTel //仅为示例
					});
				} else if (e.index === 2) {
                    that.Common.toUrl('/pages/mall/ShoppingCartList',true)
				}
			},

			openPopup(e) {
				if (!this.Auth.isLogin()) {
                    this.Auth.toLogin()
					return
				}

				if (e.index === 0) {
					this.popupType = 1
				} else if (e.index === 1) {
					this.popupType = 2
				}

				this.$refs.popup.open('bottom')
			},

			closePopup() {
				this.$refs.popup.close()
			},

			//下拉刷新
			onRefresh() {},

			addCart() {
				if (this.goodsInfo.id === this.goodsShowInfo.id) {
					uni.showToast({
						title: "请选择商品规格",
						icon: 'none'
					})
					return
				}

				ShoppingCartApi.add({
					goodsId: this.goodsShowInfo.id,
					goodsNum: this.goodsNum
				}).then((response) => {
					this.countShoppingCart()
					this.closePopup()
				})

			},

			toOrder() {
				if (this.goodsInfo.id === this.goodsShowInfo.id) {
					uni.showToast({
						title: "请选择商品规格",
						icon: 'none'
					})
					return
				}
				if(this.goodsShowInfo.goodsPrice===0){
					uni.showToast({
						title: "商家未设置商品价格，暂不支持购买",
						icon: 'none'
					})
					return
				}
				let goodsParam = [{
					goodsId: this.goodsShowInfo.id,
					goodsNum: this.goodsNum
				}]
				this.closePopup()
				uni.navigateTo({
					url: '/pages/mall/ConfirmOrder?goodsParam=' + encodeURIComponent(JSON.stringify(goodsParam))
				});
			},

			pageScrollTo(index, id) {
				this.navActiveIndex = index
				uni.pageScrollTo({
					selector: "#" + id,
					duration: 300
				});
			},
			bannerChange(e) {
				this.currentBannerIndex = e.detail.current
			}
		}
	}
</script>

<style scoped>
	.nav {
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		position: fixed;
		z-index: 999;
		left: 0;
		top: 0;
		width: 100%;
		background-color: #FFFFFF;
	}
	.nav text {
		font-size: 30rpx;
		padding: 0 50rpx;
	}
	.nav .active {
		color: #FF2F2F;
	}
	.banner {
		width: 100%;
		height: 750rpx;

        /*#ifdef MP-WEIXIN || APP-PLUS*/
		margin-top: 88rpx;
        /*#endif*/
	}
	.banner image {
		width: 100%;
		height: 100%;
	}
	.ad {
		width: 100%;
		height: 100rpx;
	}
	.ad image {
		width: 100%;
		height: 100%;
	}
	.goods-info {
		border-bottom: 1px solid #F2F2F2;
		padding: 0 32rpx 26rpx 32rpx;
	}
	.goods-info .price {
		padding: 10rpx 0;
		color: #F81200;
		font-size: 60rpx;
		font-weight: bold;
	}
	.goods-info .price text {
		font-size: 32rpx;
	}
	.goods-info .title {
		font-size: 36rpx;
		font-weight: bold;
		line-height: 40rpx;
		color: #222222;
	}
	.goods-info .summary {
		font-size: 26rpx;
		color: #5C5C5C;
		margin-top: 30rpx;
	}
	.goods-param {
		padding: 26rpx 32rpx;
	}
	.goods-param .title {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		color: #232323;
	}
	.goods-param .key-val {
		color: #5C5C5C;
		display: flex;
		line-height: 44rpx;
	}
	.goods-param .key-val .key {
		width: 160rpx;
		font-size: 26rpx;
	}
	.goods-param .key-val .val {
		flex: 1;
		font-size: 26rpx;
	}
	.goods-detail image {
		width: 100%;
	}
	.goods-carts {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		position: fixed;
		left: 0;
		right: 0;
		/* #ifdef H5 */
		left: var(--window-left);
		right: var(--window-right);
		/* #endif */
		bottom: 0;
	}
	.spec {
		border-radius: 60rpx 60rpx 0 0;
		background: #FFFFFF;
		padding: 0 30rpx 30rpx 30rpx;
		;
	}
	.spec .close {
		padding: 20rpx 0 10rpx 0;
		text-align: right;
	}
	.spec .info {
		display: flex;
	}
	.spec .info .left {
		width: 160rpx;
		height: 160rpx;
	}
	.spec .info .left image {
		width: 160rpx;
		height: 160rpx;
	}
	.spec .info .right {
		flex: 1;
		padding-left: 30rpx;
	}
	.spec .info .right .title {
		font-size: 32rpx;
		min-height: 84rpx;
	}
	.spec .info .right .price {
		font-size: 52rpx;
		color: #F81200;
		margin-top: 20rpx;
		font-weight: bold;
	}
	.spec .info .right .price text {
		font-size: 32rpx;
	}
	.spec .spec-list {
		margin-top: 44rpx;
	}
	.spec .spec-list .item {
		margin-bottom: 34rpx;
	}
	.spec .spec-list .item .spec-name {
		font-size: 34rpx;
		font-weight: bold;
		color: #232323;
	}
	.spec .spec-list .item .spec-value {
		margin-top: 22rpx;
		display: flex;
		flex-direction: row;
		-webkit-flex-wrap: wrap;
		flex-wrap: wrap;
	}
	.spec .spec-list .item .spec-value text {
		font-size: 24rpx;
		border: 1px solid #F1F1F1;
		border-radius: 40rpx;
		margin-right: 20rpx;
		padding: 14rpx 32rpx;
		margin-bottom: 20rpx;
		min-width: 80rpx;
		text-align: center;
	}
	.spec .spec-list .item .spec-value .active {
		border: 1px solid #E51422;
		color: #E51422;
		background-color: #FFF4F5;
	}
	.spec .spec-list .item .spec-value .disable {
		border: 1px solid #F1F1F1;
		color: #CCCCCC;
		background-color: #EEEEEE;
	}
	.spec .spec-num {
		display: flex;
		margin-bottom: 54rpx;
	}
	.spec .spec-num .left {
		flex: 1;
		font-size: 34rpx;
		font-weight: bold;
		color: #232323;
	}
	.spec .spec-num .right {
		width: 200rpx;
	}
	::v-deep .uni-numbox-btns {
		border-radius: 5px !important;
	}
	::v-deep .uni-numbox--text {
		color: #C0C0C0 !important;
	}
	::v-deep .uni-numbox__value {
		background: none !important;
		font-weight: bold;
	}
	::v-deep .uni-input-input {
		pointer-events: none;
	}
	.spec-btn {
		background-color: #FF3535;
		border-radius: 50rpx;
	}
</style>
